package com.lazycat.backend.service.impl.cart;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lazycat.backend.mapper.GoodMapper;
import com.lazycat.backend.mapper.OrderMapper;
import com.lazycat.backend.mapper.ShoppingCarMapper;
import com.lazycat.backend.mapper.StoreMapper;
import com.lazycat.backend.pojo.Good;
import com.lazycat.backend.pojo.Orders;
import com.lazycat.backend.pojo.Store;
import com.lazycat.backend.pojo.UserShoppingCar;
import com.lazycat.backend.service.cart.CheckOutAllInCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CheckOutAllInCartServiceImpl implements CheckOutAllInCartService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShoppingCarMapper shoppingCarMapper;

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Override
    public Map<String, Object> checkOut(Integer userId, Integer addressId) {
        HashMap<String, Object> resp = new HashMap<>();
        // 拉去所有购物车商品
        QueryWrapper<UserShoppingCar> userShoppingCarQueryWrapper = new QueryWrapper<>();
        userShoppingCarQueryWrapper.eq("user_id", userId);
        List<UserShoppingCar> userShoppingCars = shoppingCarMapper.selectList(userShoppingCarQueryWrapper);
        for (UserShoppingCar userShoppingCar : userShoppingCars) {
            Integer goodId = userShoppingCar.getGoodId();

            QueryWrapper<Good> goodQueryWrapper = new QueryWrapper<>();
            goodQueryWrapper.eq("id", goodId);
            Good good = goodMapper.selectOne(goodQueryWrapper);
            //更新买家
            good.setBuyerId(userId);
            goodMapper.update(good, goodQueryWrapper);



            //增加一条订单
            QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<>();
            storeQueryWrapper.eq("id", good.getStoreId());
            Store store = storeMapper.selectOne(storeQueryWrapper);
            Orders newOrder = new Orders(userId, store.getUserId(), good.getId(), new Date().toString(), addressId);
            orderMapper.insert(newOrder);

            //从购物车中删除
            QueryWrapper<UserShoppingCar> userShoppingCarQueryWrapper1 = new QueryWrapper<>();
            userShoppingCarQueryWrapper1.eq("user_id", userId);
            userShoppingCarQueryWrapper1.eq("good_id", goodId);
            shoppingCarMapper.delete(userShoppingCarQueryWrapper1);
        }

        resp.put("error_message", "success");
        return resp;
    }
}
